<template>
<div style="margin-top: 20px">
  <h2>资金追踪</h2>
  <SearchView />
  <div>
    <p>追踪层级</p>
    <el-select
      v-model="subTaskStore.active_level"
      placeholder="Select"
      style="width: 100px"
      @change="handleChange"
    >
      <el-option
        v-for="item in subTaskStore.level_option"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </div>
  <br>
  <div>
    <el-button type="success" @click="track">追踪</el-button>
    <el-button type="warning" @click="save">保存</el-button>
  </div>

  <el-table
    ref="multipleTableRef"
    :data="subTaskStore.tableData"
    style="width: 100%"
    height="540"
    @selection-change="handleSelectionChange"
    @row-dblclick="editable"

  >
    <el-table-column fixed="left" type="selection" width="55" selected  />
    <el-table-column property="id" width="50" label="id" />
    <el-table-column property="j_y_k_h" width="160" label="交易卡号" />
    <el-table-column property="j_y_z_h" width="160" label="交易账号" />

    <el-table-column property="j_y_h_m" width="160" label="交易户名" />
    <el-table-column property="j_y_z_j_h_m" width="180" label="交易证件号码" />
    <el-table-column property="j_y_s_j" width="165" label="交易时间" />
    <el-table-column property="j_y_j_e" width="130" label="交易金额" />
    <el-table-column property="j_y_y_e" width="130" label="交易余额" />
    <el-table-column property="s_f_b_z" label="收付标志" />
    <el-table-column property="j_y_d_s_z_h" width="160" label="交易对手账卡号" />
    <el-table-column property="x_j_b_z" label="现金标志" />
    <el-table-column property="d_s_h_m" width="160" label="对手户名" />
    <el-table-column property="d_s_s_f_z_h" width="160" label="对手身份证号" />
    <el-table-column property="d_s_k_h_y_h" width="200" label="对手开户银行" />
    <el-table-column property="z_y_s_m" width="160" label="摘要说明" />
    <el-table-column property="j_y_b_z" label="交易币种" />
    <el-table-column property="j_y_w_d_m_c" width="200" label="交易网点名称" />
    <el-table-column property="j_y_f_s_d" label="交易发生地" />
    <el-table-column property="j_y_s_f_c_g" label="交易是否成功" />
    <el-table-column property="p_h" label="传票号" />
    <el-table-column property="IP_d_z" label="IP地址" />
    <el-table-column property="MAC_d_z" label="MAC地址" />
    <el-table-column property="d_s_j_y_y_e" label="对手交易余额" />
    <el-table-column property="j_y_l_s_h" width="160" label="交易流水号" />
    <el-table-column property="r_z_h" width="160" label="日志号" />
    <el-table-column property="p_z_z_l" width="160" label="凭证种类" />
    <el-table-column property="p_z_h" width="160" label="凭证号" />
    <el-table-column property="j_y_g_y_h_h" width="160" label="交易柜员号" />
    <el-table-column property="b_z" width="160" label="备注" />
    <el-table-column property="s_h_m_c" width="160" label="商户名称" />
    <el-table-column property="s_h_d_m" width="160" label="商户代码" />
    <el-table-column property="j_y_l_x" width="160" label="交易类型" />
    <el-table-column property="c_x_f_k_j_g_y_y_y" width="160" label="查询反馈结果原因" />
    <el-table-column fixed="right" label="操作" width="120">
      <template #default>
        <el-button disabled
          size="small"
          type="danger"
          @click="del"
        >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>
  <div class="page_right">
    <el-pagination
      @current-change="subTaskStore.current_change"
      background
      layout="total,prev, pager, next"
      :total="subTaskStore.total"
      default-page-size="subTaskStore.pageSize"
    />
  </div>
  <el-dialog v-model="dialogVisible" title="修改字段">
    <el-form>
      <el-form-item label="交易户名">
        <el-input v-model="dialogForm.j_y_h_m"></el-input>
      </el-form-item>

      <el-form-item label="交易对手卡号">
        <el-input v-model="dialogForm.j_y_d_s_z_h"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="dialogVisibleSubmit" type="primary">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</div>
<!--//弹出模态框-->

</template>

<script lang="ts" setup>
import { ref,reactive ,nextTick } from 'vue'
import {ElMessage, ElTable} from 'element-plus'
import {useSubTaskStore} from '../stores/index'
import SearchView from "./SearchView.vue";
const subTaskStore = useSubTaskStore()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<[]>([])

const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value!.clearSelection()
  }
}
const del = () => {

}

const dialogForm = ref({
  id:"",
  j_y_h_m:"",
  j_y_d_s_z_h:""
})
const dialogVisibleSubmit = () => {

  const sql = `UPDATE "main"."transaction_table_${subTaskStore.detail.p_id}" SET j_y_h_m='${dialogForm.value.j_y_h_m}',  j_y_d_s_z_h=${dialogForm.value.j_y_d_s_z_h} WHERE id=${dialogForm.value.id}`
  window.send_main.exec_db(sql,(result) =>{
    dialogVisible.value = false
  })


}
const dialogVisible = ref(false)
const editable = (row, column, event) => {
  dialogForm.value.j_y_h_m = row.j_y_h_m
  dialogForm.value.j_y_d_s_z_h = row.j_y_d_s_z_h
  dialogForm.value.id = row.id
  dialogVisible.value = true
}
const handleSelectionChange = (rows) => {
  rows.forEach((row) => {
    subTaskStore.selected_ids.add(row.id);//添加ID进去
    subTaskStore.parent_j_y_d_s_z_h.add(row.j_y_d_s_z_h);//添加交易号进去
  });
}
//保存
const save = async () => {
  let value = ``
  const level = subTaskStore.active_level //当前层级
  const sub_task_id = subTaskStore.detail.id //子任务ID

  let p_id = 0 //上一层的ID
  if (level > 1) {
    p_id = 0 //TODO:如果不是第一层，那么ID就不是0,就是上一层的ID
  }
  if (subTaskStore.selected_ids.length === 0) {
    ElMessage.error('错误, 未选择交易！')
  }

  for (const id of subTaskStore.selected_ids) {
    const query_sql = `SELECT COUNT(*) AS a FROM track WHERE transaction_table_id=${id} AND sub_task_id=${sub_task_id}`
    await new Promise((resolve, reject) => {
      window.send_main.query_db(query_sql, (result) => {
        if (result[0].a === 0) {
          value += `,(${id},${level},${sub_task_id},${p_id})`
        }
        resolve();
      });
    });
  }

  if (value != "") {
    // 查询完成后执行插入操作
    const insert_sql = `INSERT INTO track ( transaction_table_id, level, sub_task_id, parent_id) VALUES ${value.substring(1)}`
    window.send_main.exec_db(insert_sql, (result) => {
      console.log(result)
      if (result.error) {
        ElMessage.error("保存失败！")
      } else {
        ElMessage.success("保存成功！")
      }
    });
  } else {
    ElMessage.error("保存失败，未修改!")
  }

}

//追踪
const track = async () => {
  //清空当前搜索条件 TODO

  //先保存
  let value = ``
  const level = subTaskStore.active_level //当前层级
  const sub_task_id = subTaskStore.detail.id //子任务ID
  let p_id = 0 //上一层的ID
  if (level > 1) {
    p_id = 0 //TODO:如果不是第一层，那么ID就不是0,就是上一层的ID
  }
  if (subTaskStore.selected_ids.length == 0) {
    ElMessage.error('错误, 未选择交易！')
  }
  for (const id of subTaskStore.selected_ids) {
    const query_sql = `SELECT COUNT(*) AS a FROM track WHERE transaction_table_id=${id} AND sub_task_id=${sub_task_id}`
    await new Promise((resolve, reject) => {
      window.send_main.query_db(query_sql, (result) => {
        if (result[0].a === 0) {
          value += `,(${id},${level},${sub_task_id},${p_id})`
        }
        resolve();
      });
    });
  }

  if (value != "") {
    // 查询完成后执行插入操作
    const insert_sql = `INSERT INTO track ( transaction_table_id, level, sub_task_id, parent_id) VALUES ${value.substring(1)}`
    window.send_main.exec_db(insert_sql, (result) => {
    });
  }
  //然后清空条件->新增条件搜索
  //清空
  subTaskStore.parent_j_y_d_s_z_h = new Set()

  subTaskStore.track_init()
}

//切换到不同层级
const handleChange = (value) => {
  subTaskStore.handleChange(value)
}
</script>
<style>
.page_right{
  float: right;
}
.search_container {
  display: flex; /* 将容器设置为弹性盒子布局 */
  justify-content: flex-start; /* 水平方向上左对齐 */
  align-items: center; /* 垂直方向上居中对齐 */
}

.search_container .item {
  margin-right: 10px; /* 子元素之间的间距 */
}
</style>
